package com.lagou.dubbo.web.util;

import com.alibaba.dubbo.rpc.support.RpcUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * tp90
 */
@Activate(group = CommonConstants.CONSUMER)
public class MonitorFilter implements Filter {

    private Logger log = LoggerFactory.getLogger(getClass());

    //一个method对应一个监听器对象。
    private Map<String, MonitorBean> methodMonitor = new ConcurrentHashMap<>();

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        //invoker.getUrl().
        boolean async = RpcUtils.isAsync(invoker.getUrl(), invocation);
        long start = System.currentTimeMillis();
        Class c = invoker.getInterface();
        if(!"MonitorService".equalsIgnoreCase(c.getSimpleName())) {
            return invoker.invoke(invocation);
        }
        String methodName = invocation.getMethodName();
        try {
            return invoker.invoke(invocation);
        } finally {
            long cost = System.currentTimeMillis() - start;
            if (!async) {
                MonitorBean bean = methodMonitor.get(methodName);
                if (bean == null) {
                    bean = new MonitorBean(methodName);
                    methodMonitor.put(methodName, bean);
                }
                bean.addCost(cost);
            }
        }
    }
}
